import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, message as msg, Modal} from 'antd';
import {PAGE, TABLE, PAGINATION_OPTIONS, FORM_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, DATE_FORMAT} from '../constants';
import TextInput from 'Shared/components/TextInput';
import {formatDateTime, conventEnumValueToString} from '../utils';
import SelectAlert from '../common/SelectAlert';
import {vehicleStatus, vehicleProperty} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';
import {conventSorter, computeSelectedRows} from './utils';
import DateRangePicker from 'Shared/components/DateRangePicker';
import styles from './style.css';
import moment from 'moment';
import {getVehicleSold} from './api';
import {injectIntl, language} from './intl';
const FormItem = Form.Item;
const MultiSelectAlert = SelectAlert.Multi;

const vehicleStatusTolist = vehicleStatus.toList(language);
class VehicleSoldSelectPanel extends PureComponent {
    state = {
        code: this.props.code,
        vin: '',
        status: undefined,
        licensePlate: '',
        engineCode: '',
        saleDate: [],
        cellPhoneNumber: '',
        customerSoldName: '',
        isFetching: false,
        data: {},
        message: '',
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        currentCondition: {},
        selectedRowKeys: [],
        selectedRows: []
    }
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = this.state.currentCondition;
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: PAGE.index
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }

    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }

    onQuery = condition => {
        this.setState({isFetching: true});
        getVehicleSold(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }
    onClickSearchBtn = () => {
        const condition = {
            code: this.state.code,
            vin: this.state.vin,
            status: this.state.status,
            licensePlate: this.state.licensePlate,
            engineCode: this.state.engineCode,
            saleDate: this.state.saleDate,
            cellPhoneNumber: this.state.cellPhoneNumber,
            customerSoldName: this.state.customerSoldName,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        const saleDateDate = (condition = {}) => {
            const {saleDate, ...others} = condition;
            if(!saleDate || saleDate.length === 0) return condition;
            return {
                ...others,
                beginSaleDateDate: moment(saleDate[0]).toISOString(),
                endSaleDateDate: moment(saleDate[1]).toISOString(),
            };
        };
        this.onQuery(saleDateDate(condition));
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    onChange = (value, name) => {
        this.setState({[name]: value});
    }

    onClickReset = () => {
        this.setState({
            code: this.props.code,
            vin: '',
            status: undefined,
            licensePlate: '',
            engineCode: '',
            saleDate: [],
            cellPhoneNumber: '',
            customerSoldName: '',
        });
    }

    onChangeRadio = (selectedRowKeys, selectedRows) => {
        this.setState({
            selectedRowKeys,
            selectedRows
        });
    }

    onCloseTag = () => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: []
        });
    }

    onSubmit = () => {
        if(!this.state.selectedRows.length)
            return msg.warn(this.props.intl.formatMessage({
                id: 'vehicleSoldSelectPanel.validate.PartClaimReports',
                defaultMessage: '请选择车辆信息'
            }));
        this.props.onSelect(this.state.selectedRows);
    }
    
    render() {
        const {formatMessage} = this.props.intl;
        const {isFetching, data, message} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.vin',
                    defaultMessage: 'VIN'
                }),
                dataIndex: 'vin',
                sorter: true
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.vehicleProperty',
                    defaultMessage: '车辆属性'
                }),
                dataIndex: 'vehicleProperty',
                render: text => conventEnumValueToString(vehicleProperty, text)
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.productCategoryCode',
                    defaultMessage: '车型编号'
                }),
                dataIndex: 'productCategoryCode',
                sorter: true
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.productCategoryName',
                    defaultMessage: '车型名称'
                }),
                dataIndex: 'productCategoryName',
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.mileage',
                    defaultMessage: '里程'
                }),
                dataIndex: 'mileage',
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.licensePlate',
                    defaultMessage: '车牌号'
                }),
                dataIndex: 'licensePlate',
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.invoiceDate',
                    defaultMessage: '开发票日期'
                }),
                dataIndex: 'invoiceDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.engineCode',
                    defaultMessage: '发动机号'
                }),
                dataIndex: 'engineCode',
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.transmissionSn',
                    defaultMessage: '变速箱号'
                }),
                dataIndex: 'transmissionSn',
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.productionDate',
                    defaultMessage: '生产日期'
                }),
                dataIndex: 'productionDate',
                sorter: true,
                render: text => formatDateTime(text, DATE_FORMAT)
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.saleDate',
                    defaultMessage: '实销日期'
                }),
                dataIndex: 'saleDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                sorter: true,
                render: text => conventEnumValueToString(vehicleStatus, text)
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.salesDealerCode',
                    defaultMessage: '服务站编号'
                }),
                dataIndex: 'salesDealerCode',
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.salesDealerName',
                    defaultMessage: '服务站名称'
                }),
                dataIndex: 'salesDealerName',
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.customerSoldCode',
                    defaultMessage: '客户编号'
                }),
                dataIndex: 'customerSoldCode',
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.customerSoldName',
                    defaultMessage: '客户姓名'
                }),
                dataIndex: 'customerSoldName',
                sorter: true,
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.cellPhoneNumber',
                    defaultMessage: '客户电话'
                }),
                dataIndex: 'cellPhoneNumber',
            },
            {
                title: formatMessage({
                    id: 'vehicleSoldSelectPanel.column.address',
                    defaultMessage: '客户地址'
                }),
                dataIndex: 'address',
            },
        ];
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                const rows = computeSelectedRows(this.state.selectedRowKeys, this.state.selectedRows, selectedRowKeys, selectedRows);
                this.setState({
                    selectedRowKeys,
                    selectedRows: rows
                });
            }
        };
        return (
            <Modal
                title={formatMessage({
                    id: 'vehicleSoldSelectPanel.show.PartClaimReportsQuery',
                    defaultMessage: '车辆信息查询'
                })}
                width="60%"
                maskClosable={false}
                footer={null}
                destroyOnClose={true}
                wrapClassName={styles.dataSelectModal}
                visible={true}
                onCancel={this.props.onCancel}>
                <Row className="form-standard">
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'vehicleSoldSelectPanel.show.code',
                            defaultMessage: '车型编号'
                        })}
                        {...FORM_OPTIONS.item}>
                            <TextInput
                                name="code"
                                value={this.state.code}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'vehicleSoldSelectPanel.show.vin',
                            defaultMessage: 'VIN'
                        })}
                        {...FORM_OPTIONS.item}>
                            <TextInput
                                name="vin"
                                value={this.state.vin}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'vehicleSoldSelectPanel.show.status',
                            defaultMessage: '状态'
                        })}
                        {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="status"
                                options={vehicleStatusTolist}
                                value={this.state.status}
                                onChange={this.onChange}/>
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'vehicleSoldSelectPanel.show.licensePlate',
                            defaultMessage: '车牌号'
                        })}
                        {...FORM_OPTIONS.item}>
                            <TextInput
                                name="licensePlate"
                                value={this.state.licensePlate}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'vehicleSoldSelectPanel.show.engineCode',
                            defaultMessage: '发动机号'
                        })}
                        {...FORM_OPTIONS.item}>
                            <TextInput
                                name="engineCode"
                                value={this.state.engineCode}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'vehicleSoldSelectPanel.show.saleDate',
                            defaultMessage: '实销日期'
                        })}
                        {...FORM_OPTIONS.item}>
                            <DateRangePicker
                                name="saleDate"
                                value={this.state.saleDate}
                                onChange={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'vehicleSoldSelectPanel.show.cellPhoneNumber',
                            defaultMessage: '客户电话'
                        })}
                        {...FORM_OPTIONS.item}>
                            <TextInput
                                name="cellPhoneNumber"
                                value={this.state.cellPhoneNumber}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'vehicleSoldSelectPanel.show.customerSoldName',
                            defaultMessage: '客户姓名'
                        })}
                        {...FORM_OPTIONS.item}>
                            <TextInput
                                name="customerSoldName"
                                value={this.state.customerSoldName}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col} className={styles['inline-button']}>
                        <Button
                            type="primary"
                            loading={isFetching}
                            onClick={this.onClickSearchBtn}>
                            {formatMessage({
                                id: 'vehicleSoldSelectPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                        <Button key="clear" onClick={this.onClickReset}>{formatMessage({
                            id: 'vehicleSoldSelectPanel.btn.reset',
                            defaultMessage: '重置'
                        })}</Button>
                    </Col>
                </Row>
                <Divider className={styles.divider}/>
                <MultiSelectAlert data={this.state.selectedRows}
                    onConfirm={this.onSubmit}
                    onDelete={this.onCloseTag}
                    onDeleteAll={this.onCloseTag}/>
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={data.content}
                    rowClassName={styles.tableCursor}
                    columns={columns}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    rowSelection={rowSelection}
                    locale={{
                        emptyText: message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                    }}
                    {...TABLE}/>
            </Modal >
        );
    }
}

VehicleSoldSelectPanel.propTypes = {
    onSelect: PropTypes.func.isRequired,
    code: PropTypes.string,
    intl: PropTypes.object,
    onCancel: PropTypes.func,
};

export default injectIntl(VehicleSoldSelectPanel);
